import { ModernBaseService } from './base/ModernBaseService';
import { DIContainer } from '../infrastructure/di';
import { configKey, config } from "../config";
import { Icard2 } from "../core/tool/Icard2";
import common from "../core/tool/common";

/**
 * 现代化血统服务
 * 使用依赖注入和现代架构模式
 */
export class ModernTalentService extends ModernBaseService {
    
    constructor(container?: DIContainer) {
        super(container);
    }

    async init(): Promise<void> {
        console.log('ModernTalentService initialized successfully');
    }

    async destroy(): Promise<void> {
        console.log('ModernTalentService destroyed');
    }

    getServiceName(): string {
        return 'ModernTalentService';
    }

    /**
     * 添加血统经验
     * @param currentTalents 当前血统列表
     * @param exp 经验值
     * @returns 添加结果
     */
    addExperience(currentTalents: any[], exp: number): {
        success: boolean;
        message: string;
        newTalentList: any[];
        levelUpMessages: string[];
    } {
        try {
            if (!currentTalents || currentTalents.length === 0) {
                return {
                    success: false,
                    message: '没有血统可以添加经验',
                    newTalentList: currentTalents || [],
                    levelUpMessages: []
                };
            }

            if (exp <= 0) {
                return {
                    success: false,
                    message: '经验值必须大于0',
                    newTalentList: currentTalents,
                    levelUpMessages: []
                };
            }

            const newTalentList = [...currentTalents];
            const levelUpMessages: string[] = [];
            const expPerTalent = Math.floor(exp / newTalentList.length);
            let remainingExp = exp % newTalentList.length;

            // 为每个血统平均分配经验
            for (let i = 0; i < newTalentList.length; i++) {
                const talent = newTalentList[i];
                let expToAdd = expPerTalent;
                
                // 将剩余经验分配给前几个血统
                if (remainingExp > 0) {
                    expToAdd += 1;
                    remainingExp--;
                }

                const oldLevel = talent.level || 1;
                const oldExp = talent.exp_now || 0;
                const oldMaxExp = talent.exp_max || this.getExpRequirement(talent.id, oldLevel);

                // 检查最大等级限制
                const maxLevel = this.getMaxLevel(talent.id);
                if (oldLevel >= maxLevel) {
                    continue; // 已达到最大等级，跳过
                }

                let newExp = oldExp + expToAdd;
                let newLevel = oldLevel;
                let newMaxExp = oldMaxExp;

                // 检查是否升级
                while (newExp >= newMaxExp && newLevel < maxLevel) {
                    newExp -= newMaxExp;
                    newLevel++;
                    newMaxExp = this.getExpRequirement(talent.id, newLevel);
                    
                    levelUpMessages.push(`血统 ${talent.id} 升级到 ${newLevel} 级！`);
                }

                // 如果达到最大等级，经验值设为0
                if (newLevel >= maxLevel) {
                    newExp = 0;
                    newMaxExp = 0;
                }

                // 更新血统数据
                talent.level = newLevel;
                talent.exp_now = newExp;
                talent.exp_max = newMaxExp;
            }

            return {
                success: true,
                message: `成功添加 ${exp} 点血统经验`,
                newTalentList: newTalentList,
                levelUpMessages: levelUpMessages
            };

        } catch (error) {
            console.error('Failed to add talent experience:', error);
            return {
                success: false,
                message: '添加血统经验失败',
                newTalentList: currentTalents,
                levelUpMessages: []
            };
        }
    }

    /**
     * 添加血统
     * @param currentTalents 当前血统列表
     * @param talentId 血统ID
     * @param count 数量
     * @returns 添加结果
     */
    addTalent(currentTalents: any[], talentId: string, count: number): {
        success: boolean;
        message: string;
        newTalentList: any[];
        levelChanged: boolean;
    } {
        try {
            const talentConfig = config.get(configKey.配置_血统)?.get(talentId);
            if (!talentConfig) {
                return {
                    success: false,
                    message: '血统不存在',
                    newTalentList: currentTalents,
                    levelChanged: false
                };
            }

            let newTalentList = [...currentTalents];
            let levelChanged = false;

            // 执行count次血统添加
            for (let i = 0; i < count; i++) {
                const existingTalent = newTalentList.find(item => item.id === talentId);
                
                if (!existingTalent) {
                    // 添加新血统
                    const newTalent = {
                        id: talentId,
                        level: 1,
                        quality: talentConfig.quality || 0,
                        exp_now: 0,
                        exp_max: this.getExpRequirement(talentId, 1)
                    };
                    newTalentList.push(newTalent);
                    levelChanged = true;
                } else {
                    // 血统已存在，增加经验或等级
                    if (existingTalent.quality < (talentConfig.quality || 0)) {
                        existingTalent.quality = talentConfig.quality || 0;
                        levelChanged = true;
                    }
                }
            }

            return {
                success: true,
                message: `成功添加血统 ${talentId} x${count}`,
                newTalentList: newTalentList,
                levelChanged: levelChanged
            };

        } catch (error) {
            console.error('Failed to add talent:', error);
            return {
                success: false,
                message: '添加血统失败',
                newTalentList: currentTalents,
                levelChanged: false
            };
        }
    }

    /**
     * 获取血统配置
     * @param id 血统ID
     * @returns 血统配置
     */
    private getTalentConfig(id: string): any {
        const cfg = config.get(configKey.配置_血统)?.get(id);
        if (!cfg) {
            console.warn(`血统配置不存在: ${id}`);
            return null;
        }
        return cfg;
    }

    /**
     * 获取血统最大等级
     * @param id 血统ID
     * @returns 最大等级
     */
    private getMaxLevel(id: string): number {
        const cfg = this.getTalentConfig(id);
        if (!cfg || !cfg.table) {
            return 1;
        }
        return cfg.table.split('\n').length;
    }

    /**
     * 获取指定等级所需经验
     * @param talentId 血统ID
     * @param level 等级
     * @returns 所需经验
     */
    private getExpRequirement(talentId: string, level: number): number {
        const cfg = this.getTalentConfig(talentId);
        if (!cfg || !cfg.table) {
            return 100; // 默认经验需求
        }

        const lines = cfg.table.split('\n');
        if (level <= 0 || level > lines.length) {
            return 100;
        }

        // 解析对应等级行的经验需求
        const line = lines[level - 1];
        if (!line) {
            return 100;
        }

        // 这里需要根据实际的表格格式来解析
        // 假设格式是类似 "level|exp|other_data"
        const parts = line.split('|');
        if (parts.length >= 2) {
            const expPart = parts[1];
            const expMatch = expPart.match(/(\d+)/);
            if (expMatch) {
                return parseInt(expMatch[1], 10);
            }
        }

        // 如果解析失败，使用默认公式
        return level * 100;
    }

    /**
     * 获取血统详情
     * @param talentId 血统ID
     * @returns 血统详情
     */
    getTalentDetails(talentId: string): {
        success: boolean;
        talent?: {
            id: string;
            name: string;
            description: string;
            quality: number;
            maxLevel: number;
        };
        message?: string;
    } {
        try {
            const cfg = this.getTalentConfig(talentId);
            if (!cfg) {
                return {
                    success: false,
                    message: '血统不存在'
                };
            }

            return {
                success: true,
                talent: {
                    id: talentId,
                    name: cfg.name || talentId,
                    description: cfg.description || '',
                    quality: cfg.quality || 0,
                    maxLevel: this.getMaxLevel(talentId)
                }
            };

        } catch (error) {
            console.error('Failed to get talent details:', error);
            return {
                success: false,
                message: '获取血统详情失败'
            };
        }
    }

    /**
     * 计算血统属性加成
     * @param talentList 血统列表
     * @returns 属性加成
     */
    calculateTalentAttributes(talentList: any[]): { [key: string]: number } {
        const totalAttributes: { [key: string]: number } = {};

        try {
            talentList.forEach(talent => {
                const cfg = this.getTalentConfig(talent.id);
                if (cfg && cfg.attributes) {
                    const level = talent.level || 1;
                    // 根据等级计算属性加成
                    Object.keys(cfg.attributes).forEach(attr => {
                        const baseValue = cfg.attributes[attr] || 0;
                        const levelMultiplier = level;
                        const value = baseValue * levelMultiplier;
                        
                        totalAttributes[attr] = (totalAttributes[attr] || 0) + value;
                    });
                }
            });
        } catch (error) {
            console.error('Failed to calculate talent attributes:', error);
        }

        return totalAttributes;
    }
}
